<template>
  <inline-Modal :visible="visible">
    <div class="annotationsListPage-container">
      <div class="screen-conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <a-select
              placeholder="请选择图纸名称"
              class="project-select"
              v-model="condition.cadFileUuid"
              @change="changeDrawing()"
            >
              <a-select-option
                :value="item.uuid"
                v-for="item in drawingSource"
                :key="item.uuid"
              >
                {{ item.fileName }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="operate">
            <!-- <a-button class="cu-btn-primary" icon="search" @click="search()">
              查询
            </a-button>
            <a-button class="cu-btn-filter" icon="reload" @click="reset()">
              重置
            </a-button> -->
            <a-button class="back-button" @click="goBack()">返回</a-button>
          </template>
        </ScreenConditions>
      </div>
      <!--  -->
      <div class="annotationsListPage-body" ref="pageDrawingVisual-container">
        <div class="loading-warp" v-if="displayValue != 4 || loading">
          <a-spin size="large" />
          <div class="tip" v-if="displayValue != 4">{{ displayName }}</div>
        </div>

        <!-- fabric画布容器 -->
        <div class="fabric-drawing-board" v-if="fabricDrawerType">
          <canvas id="fabricCanvasContainer"></canvas>
        </div>
        <!-- bim容器 -->
        <div class="BlackHole-container" ref="blackHoleContainer"></div>
      </div>

      <!-- fabric-toolbar工具栏 -->
      <div class="fabric-toolbar-container" v-if="annotationsDrawer.fabric">
        <div class="toolContainer">
          <div
            class="itemView"
            v-for="(item, index) in fabricBarSource"
            :key="item.type"
            @click="handelFabricToolbar(item, index)"
            :class="fabricBarActiveIndex == item.type && 'active'"
          >
            <icon-fonts :icon="item.icon" :size="20" />
          </div>
          <div class="divider"></div>
          <div class="itemView" @click="fabricRevocation()">
            <icon-fonts icon="icon-fanhui1" :size="20" />
          </div>
          <div class="graphic-button">
            <div class="space-item" @click="handelFabricClose()">取消</div>
            <div class="space-item" @click="handelFabricOk()">完成</div>
          </div>
        </div>
        <div
          class="stylePickerContainer"
          :style="{ marginLeft: annotationsDrawer.pickerLeft + 'px' }"
          v-if="fabricBarActiveIndex"
        >
          <div class="arrow"></div>
          <div class="stylePickerWrapper">
            <a-slider
              v-model="annotationsDrawer.sliderValue"
              :min="1"
              :max="annotationsDrawer.maxValue"
            />
            <div class="text">{{ annotationsDrawer.sliderValue }}</div>
            <div class="divider"></div>
            <div class="color-list">
              <div
                class="colorItem"
                v-for="(item, index) in colorBarSource"
                :key="index"
                :style="{ backgroundColor: item }"
                :class="[annotationsDrawer.colorActive == index && 'active']"
                @click="handelColor(item, index)"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 批注列表  -->
    <annotationsDrawer
      ref="annotationsDrawerRef"
      :visible.sync="annotationsDrawer.visible"
      @handleOpenList="handleOpenList()"
      @open="handleFabricOpen()"
      @editSave="handleEditSave($event)"
    >
    </annotationsDrawer>

    <!-- 新增批注 -->
    <addAnnotationsModal
      :visible.sync="addAnnotationsModal.visible"
      :operateType.sync="addAnnotationsModal.operateType"
      :parameter="addAnnotationsModal.soucre"
      :snapshot="addAnnotationsModal.snapshot"
      :reOpen.sync="addAnnotationsModal.reOpen"
      @refresh="refreshAnnotationData($event)"
    ></addAnnotationsModal>
  </inline-Modal>
</template>

<script>
//新增
import fabricMixin from "./fabricMixin";
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { canvasHolder } from "@/blackHoleTools/CanvasHolder";
import { releaseEngine, initialSDKModule } from "@/blackHoleTools/Engine";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
//批注列表
import annotationsDrawer from "./annotationsDrawer.vue";
//新增批注
import addAnnotationsModal from "./addAnnotationsModal.vue";

export default {
  inject: ["drawingModel"],
  provide() {
    return {
      fabricCanvas: () => this.canvas,
    };
  },
  mixins: [fabricMixin],
  components: {
    ScreenConditions,
    annotationsDrawer,
    addAnnotationsModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
  },
  data() {
    return {
      //查询条件
      condition: {
        //图纸名称
        cadFileUuid: undefined,
        //单位
        unit: "",
        //
      },
      //图纸列表
      annotationsDrawer: {
        //抽屉
        visible: true,
        //操作栏
        fabric: false,
        //左偏移
        pickerLeft: 0,
        //滑动默认值
        sliderValue: 5,
        //滑动最大值
        maxValue: 20,
        //颜色选中
        colorActive: 0,
        //默认颜色
        color: "#EE4844",
      },
      //图纸名称
      drawingSource: [],
      //新增批注
      addAnnotationsModal: {
        visible: false,
        operateType: 1,
        snapshot: "",
        soucre: {},
        reOpen: false,
      },
      //fabric数据
      fabricBarSource: [
        {
          type: 1,
          drawerType: "all",
          icon: "icon-huabi",
        },
        {
          type: 2,
          drawerType: "cloud",
          icon: "icon-yun",
        },
        {
          type: 3,
          drawerType: "rect",
          icon: "icon-juxing",
        },
        {
          type: 4,
          drawerType: "ellipse",
          icon: "icon-big-circle",
        },
        {
          type: 5,
          drawerType: "arrow",
          icon: "icon-jiantou",
        },
        {
          type: 6,
          drawerType: "text",
          icon: "icon-font-size-2",
        },
      ],
      //fabric数据选中
      fabricBarActiveIndex: null,
      fabricDrawerType: "",
      //颜色集合
      colorBarSource: [
        "#EE4844",
        "#FDE75B",
        "#27AF24",
        "#2DABEF",
        "#000000",
        "#9B9B99",
        "#FFFFFF",
      ],
      //
      cadSource: {},
      loading: false,
      //
      displayName: "",
      displayValue: 0,
    };
  },
  computed: {
    ...mapGetters(["blackHoleAssetsPreFetch", "blackHoleRESystemCreated"]),
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          let { current } = this.drawingModel();
          this.condition.cadFileUuid = current.uuid;
          this.condition.unit = current.unit;
          this.getDrawingData();
        }
      },
      immediate: true,
    },

    // blackHoleAssetsPreFetch: {
    //   handler(val) {
    //     this.$nextTick((_) => {
    //       if (val) {
    //         initialSDKModule();
    //       }
    //     });
    //   },
    //   immediate: true,
    // },

    // blackHoleRESystemCreated: {
    //   handler(val) {
    //     if (val) {
    //       this.$nextTick((_) => {
    //         let { cadFileUuid } = this.condition;
    //         this.$nextTick((_) => {
    //           if (cadFileUuid) {
    //             this.getSetModelData(cadFileUuid);
    //           }
    //         });
    //       });
    //     }
    //   },
    // },
  },
  mounted() {
    this.$nextTick((_) => {
      let { cadFileUuid } = this.condition;
      this.$nextTick((_) => {
        if (cadFileUuid) {
          this.getSetModelData(cadFileUuid);
        }
      });
    });

    // window.addEventListener("resize", () => {
    //   if (this.canvas) {
    //     this?.setCanvasSize();
    //   }
    // });
  },
  methods: {
    //图纸
    getDrawingData() {
      let { uuid } = this.drawingModel();
      axios
        .post(
          `/probusiness/drawingReview/getMarkCadList?uuid=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.drawingSource = res?.data ?? [];
        })
        .catch((_) => {
          this.drawingSource = [];
        });
    },

    getThreeDataList() {
      this.$refs.annotationsDrawerRef.getData();
    },

    changeDrawing() {
      let { cadFileUuid } = this.condition;
      let unit = this.drawingSource.find((v) => v.uuid == cadFileUuid).unit;
      this.condition.unit = unit;
      this.getSetModelData(cadFileUuid);
      //刷新最新三条数据
      this.$refs.annotationsDrawerRef.getData();
    },

    //刷新批注列表数据
    refreshAnnotationData(ev) {
      let { event } = ev;
      switch (event) {
        //新增
        case "add":
          this.$refs.annotationsDrawerRef.getData();
          this.annotationsDrawer.fabric = false;
          break;

        //编辑
        case "edit":
          this.$refs.annotationsDrawerRef.getData();
          this.annotationsDrawer.fabric = false;
          break;

        default:
          break;
      }
    },

    //初始化引擎引擎系统
    initEngine() {
      let canvasDom = canvasHolder.get();
      if (!canvasDom) {
        canvasDom = canvasHolder.create();
        document.body.appendChild(canvasDom);
      }
      window.BlackHole3D = window.BlackHole3D ? window.BlackHole3D : {};
      window.BlackHole3D["canvas"] = canvasDom;
      if (typeof window.BlackHole3D.RealBIMWeb === "undefined") {
        window.BlackHole3D = window.CreateBlackHoleWebSDK(window.BlackHole3D);
      }
    },

    //引擎系统初始化完成回调
    onSystemReady() {
      let containerBox = this.$refs["blackHoleContainer"];
      var sysInfo = new BlackHole3D.RESysInfo();
      //相对于html页面的RealBIMWeb_Worker.js的路径
      sysInfo.workerjsPath = "./blackhole/RealBIMWeb_Worker.js";
      //初始化图形窗口的宽度
      sysInfo.renderWidth = containerBox?.clientWidth;
      //初始化图形窗口的高度
      sysInfo.renderHieght = containerBox?.clientHeight;
      //引擎调用的公共资源的路径
      sysInfo.commonUrl =
        "http://203.156.230.22:9012/default.aspx?dir=url_res03&path=res_gol001";
      //引擎资 源发布服务配套的用户名、密码
      sysInfo.userName = "bjadmin";
      sysInfo.passWord = "Bj@123456.";
      //表示主窗口的名称,对应document.title，默认值 "BlackHole"
      sysInfo.mainWndName = document.title;
      //开始执行场景初始化，加载公共资源
      BlackHole3D.initEngineSys(sysInfo);
      console.log("引擎系统初始化完成", sysInfo, BlackHole3D);
    },

    //查询BIM地址
    getSetModelData(uuid = "") {
      this.loading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/bimCadFile/project/cadFile/list?uuid=${uuid}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.cadSource = res?.data?.[0] ?? {};
            this.displayValue = this.cadSource?.status?.value ?? 0;
            this.displayName = this.cadSource?.status?.displayName ?? "";
            this.addEventListener();
            this.initEngine();
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //系统引擎创建完成回调【加载模型资源】
    onEngineCreated() {
      let { unit } = this.condition;
      try {
        let { resourcesAddress } = this.cadSource;
        let dom = this.$refs.blackHoleContainer;
        let BlackHole3D = window.BlackHole3D;
        canvasHolder.moveCanvasToTarget(this.$refs.blackHoleContainer);
        BlackHole3D.m_re_em_window_width = dom.clientWidth;
        BlackHole3D.m_re_em_window_height = dom.clientHeight;
        BlackHole3D.setViewMode(
          BlackHole3D.REVpTypeEm.None,
          BlackHole3D.REVpTypeEm.CAD,
          BlackHole3D.REVpRankEm.Single
        );
        // console.log(resourcesAddress);
        BlackHole3D.CAD.loadCAD(
          resourcesAddress,
          BlackHole3D.RECadUnitEm[unit ?? "CAD_UNIT_Meter"],
          1.0
        );
      } catch (error) {}
    },

    //bim事件监听
    addEventListener() {
      document.addEventListener("RESystemReady", this.onSystemReady);
      document.addEventListener("RESystemEngineCreated", this.onEngineCreated);
      //场景模型加载完成回调
      document.addEventListener("RECADLoadFinish", (_) => {
        this.loading = false;
        //设置系统UI
        this.setSystemUI();
      });
      window.addEventListener("resize", this.onResize);
    },

    //设置系统UI
    setSystemUI() {
      try {
        BlackHole3D.Graphics.setGeoCoordVisible(false);
        BlackHole3D.Graphics.setSysUIPanelVisible(true);
        BlackHole3D.Graphics.setSysPanelUIDockArea(3);
        BlackHole3D.Camera.resetCamLocate();
        BlackHole3D.Camera.resetCamBound();
      } catch (error) {}
    },

    //监听窗口尺寸变化
    onResize() {
      let box = this.$refs["blackHoleContainer"];
      if (box) {
        window.BlackHole3D.m_re_em_window_width = window.innerWidth;
        window.BlackHole3D.m_re_em_window_height = window.innerHeight;
      }
    },

    //查询
    search() {},

    //重置
    reset() {
      this.condition.cadFileUuid = undefined;
    },

    //编辑批注
    handleEditSave(row) {
      this.addAnnotationsModal.operateType = 2;
      this.addAnnotationsModal.soucre = row;
      this.addAnnotationsModal.reOpen = false;
      this.annotationsDrawer.fabric = false;
      this.addAnnotationsModal.visible = true;
    },

    //打开批注toolbar
    handleFabricOpen() {
      this.annotationsDrawer.fabric = true;
    },

    //批注toolbar选择事件
    handelFabricToolbar(item) {
      let { type, drawerType } = item;
      this.fabricBarActiveIndex = type;
      this.annotationsDrawer.sliderValue = 2;
      this.annotationsDrawer.maxValue = 20;
      this.$nextTick((_) => {
        setTimeout(() => {
          !this.canvas && this.annotationsDrawer.fabric && this.initFabric();
          if (this.canvas) {
            this.canvas.defaultCursor = "default";
            this.canvas.isDrawingMode = false;
            this.canvas.freeDrawingBrush.color = "transparent";
            this.canvas.freeDrawingBrush.width = 0;
            if (drawerType == "all") {
              this.canvas.isDrawingMode = true;
              this.canvas.freeDrawingBrush.color =
                this.colorBarSource?.[
                  this.annotationsDrawer?.colorActive ?? 0
                ] ?? "red";
              this.canvas.freeDrawingBrush.width = this.annotationsDrawer.sliderValue;
            } else if (drawerType == "text") {
              this.canvas.defaultCursor = "text";
            }
          }
        }, 200);
      });
      this.fabricDrawerType = drawerType;
      //

      //
      switch (type) {
        case 1:
          this.annotationsDrawer.pickerLeft = 0;
          break;
        case 2:
          this.annotationsDrawer.pickerLeft = 56;
          break;
        case 3:
          this.annotationsDrawer.pickerLeft = 112;
          break;
        case 4:
          this.annotationsDrawer.pickerLeft = 168;
          break;
        case 5:
          this.annotationsDrawer.pickerLeft = 224;
          break;
        case 6:
          this.annotationsDrawer.pickerLeft = 280;
          this.annotationsDrawer.sliderValue = 16;
          this.annotationsDrawer.maxValue = 60;
          break;
        default:
          break;
      }
    },

    //批注toolbar确定
    handelFabricOk() {
      let allGraphArr = this.getAllGraph() ?? [];
      if (allGraphArr.length == 0) {
        this.$message.warning("暂无批注信息！");
        return;
      }
      let { reOpen } = this.addAnnotationsModal;
      if (!reOpen) {
        let { cadFileUuid } = this.condition;
        let { drawingSource } = this;
        let current = drawingSource.find((v) => v.uuid == cadFileUuid);
        let { fileCode } = current.bimCadFile;
        this.addAnnotationsModal.operateType = 1;
        this.addAnnotationsModal.soucre = {
          cadCode: fileCode,
        };
      }
      this.addAnnotationsModal.visible = true;
      setTimeout((_) => {
        this.disposeFabric();
      }, 200);
    },

    //关闭批注toolbar
    handelFabricClose() {
      this.disposeFabric();
      this.annotationsDrawer.fabric = false;
      this.fabricBarActiveIndex = null;
      this.annotationsDrawer.pickerLeft = 0;
      this.annotationsDrawer.sliderValue = 2;
      this.annotationsDrawer.maxValue = 20;
      this.annotationsDrawer.colorActive = 0;
      this.annotationsDrawer.color = "#EE4844";
    },

    //颜色点击事件
    handelColor(item, index) {
      this.annotationsDrawer.color = item;
      this.annotationsDrawer.colorActive = index;
    },

    //返回
    goBack() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    //打开批注列表
    handleOpenList() {
      this.$emit("handleListPage");
    },

    //卸载
    releaseEngine() {
      document.removeEventListener("REDataSetLoadFinish", () => {});
      document.removeEventListener("RESystemReady", () => {});
      if (typeof window.BlackHole3D?.releaseEngine != "undefined") {
        canvasHolder.moveCanvasToBody();
        window.BlackHole3D?.releaseEngine();
        window.BlackHole3D = null;
      }
    },
  },
  beforeDestroy() {
    this.disposeFabric();
    this.releaseEngine();
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  background-color: #f0f2f5;
  /deep/.header {
    display: none;
  }
  /deep/.main {
    padding: 0;
    overflow: hidden !important;
  }
  .annotationsListPage-container {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .screen-conditions-container {
      margin-bottom: 0;
    }
    .back-button {
      position: absolute;
      right: 16px;
      z-index: 999;
    }
    .annotationsListPage-body {
      flex: 1;
      background: #000;
      position: relative;
      .fabric-drawing-board {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 9;
      }

      .BlackHole-container {
        width: 100%;
        height: 100%;
      }
      .loading-warp {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        align-items: center;
        .tip {
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 16px;
          color: #fff;
          line-height: 50px;
        }
      }
    }

    .fabric-toolbar-container {
      z-index: 99;
      position: absolute;
      top: 90px;
      left: 50%;
      transform: translateX(-50%);
      user-select: none;
      .divider {
        width: 1px;
        height: 18px;
        background-color: #0c2236;
        margin: 0 8px;
        align-self: center;
      }
      .toolContainer {
        width: 556px;
        height: 48px;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 4px 4px 4px 4px;
        display: flex;
        align-items: center;
        padding: 0 8px;
        .itemView {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          border-radius: 4px 4px 4px 4px;
          margin: 4px 8px;
          cursor: pointer;
          &.active {
            background: rgba(22, 119, 255, 0.3);
            .bj-icon {
              color: #1677ff !important;
            }
          }
        }

        .graphic-button {
          display: flex;
          align-items: center;
          .space-item {
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 26px;
            border-radius: 4px 4px 4px 4px;
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            line-height: 13px;
            letter-spacing: 1px;
          }
          :nth-child(1) {
            background: #ffffff;
            color: #8c8c8c;
            margin-right: 8px;
          }
          :nth-child(2) {
            background: #1677ff;
            color: #ffffff;
          }
        }
      }
      .stylePickerContainer {
        position: absolute;
        left: 0;
        top: 56px;
        width: 272px;
        .arrow {
          width: 0;
          height: 0;
          margin-left: 28px;
          border-left: 7px solid transparent;
          border-right: 7px solid transparent;
          border-bottom: 7px solid rgba(255, 255, 255, 0.8);
        }
        .stylePickerWrapper {
          background: rgba(255, 255, 255, 0.8);
          border-radius: 4px;
          padding: 0 8px;
          display: flex;
          align-items: center;
          /deep/.ant-slider {
            width: 64px;
          }
          .text {
            min-width: 20px;
            color: #666;
            font-size: 12px;
            text-align: center;
          }
          .color-list {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .colorItem {
              cursor: pointer;
              border: 0.5px solid rgb(209, 209, 209);
              width: 17px;
              height: 17px;
              opacity: 1;
              border-radius: 2px;
              &.active {
                border: 2px solid rgb(255, 255, 255);
                box-shadow: 0 0 3px #0000005c;
              }
            }
          }
        }
      }
    }
  }
}
</style>
